import hashlib
from django.urls import reverse
from django.views import View

from studysystem.models import *
from .forms import LoginForm
from .forms import RegForm
from django.shortcuts import render, redirect

from studysystem import models, forms


def welcome(request):
    return render(request, "index.html")


def towelcome(request):
    return render(request, "index.html")


def hash_code(s, salt="studysystem"):
    h = hashlib.sha256()
    s += salt
    h.update(s.encode())  # update方法只接收bytes类型
    return h.hexdigest()


def register(request):
    if request.session.get('is_login', None):
        # 登录状态不允许注册。你可以修改这条原则！
        return redirect(request.GET.get('from', reverse('welcome')))
    if request.method == "POST":
        register_form = RegForm(request.POST)
        message = "请检查填写的内容！"
        if register_form.is_valid():  # 获取数据
            username = register_form.cleaned_data['uname']
            password1 = register_form.cleaned_data['pwd']
            password2 = register_form.cleaned_data['repwd']
            if password1 != password2:  # 判断两次密码是否相同
                message = "两次输入的密码不同！"
                return render(request, 'register.html', locals())
            else:
                same_name_user = models.usertable.objects.filter(username=username)
                if same_name_user:  # 用户名唯一
                    message = '用户已经存在，请重新选择用户名！'
                    return render(request, 'register.html', locals())

                # 当一切都OK的情况下，创建新用户

                new_user = models.usertable.objects.create()
                new_user.username = username
                new_user.password = hash_code(password1)  # 使用加密密码
                new_user.save()
                return redirect(request.GET.get('from', reverse('login')))  # 自动跳转到登录页面
    register_form = RegForm()
    return render(request, 'register.html', locals())


def login(request):
    if request.session.get('is_login', None):
        return redirect(request.GET.get('from', reverse('welcome')))
    if request.method == "POST":
        login_form = LoginForm(request.POST)
        message = "请检查填写的内容！"
        if login_form.is_valid():
            username = login_form.cleaned_data['uname']
            password = login_form.cleaned_data['pwd']
            try:
                user = models.usertable.objects.get(username=username)
                if user.password == hash_code(password):  # 哈希值和数据库内的值进行比对
                    request.session['is_login'] = True
                    request.session['user_id'] = user.id
                    request.session['user_username'] = user.username
                    return redirect(request.GET.get('from', reverse('welcome')))
                else:
                    message = '密码不正确'
            except:
                message = '用户不存在'
        return render(request, 'login.html', locals())

    login_form = LoginForm()
    return render(request, 'login.html', locals())


def logout(request):
    if not request.session.get('is_login', None):
        return redirect(request.GET.get('from', reverse('welcome')))
    request.session.flush()

    return redirect(request.GET.get('from', reverse('welcome')))


def pretest(request):
    if request.session.get('is_login', None):
        return render(request, "pretest.html")
    else:
        return redirect(request.GET.get('from', reverse('welcome')))


def bstudy(request):
    if request.session.get('is_login', None):
        return render(request, "bstudy.html")
    else:
        return redirect(request.GET.get('from', reverse('welcome')))


def bstudy4(request):
    if request.session.get('is_login', None):
        return render(request, "bstudy4.html")
    else:
        return redirect(request.GET.get('from', reverse('welcome')))


def bstudy5(request):
    if request.session.get('is_login', None):
        return render(request, "bstudy5.html")
    else:
        return redirect(request.GET.get('from', reverse('welcome')))


class TestPaperAdd(View):
    def get(self, request):
        if request.session.get('is_login', None):
            exercise_obj1 = exercise.objects.filter(type=0).order_by('?')[:5]
            exercise_obj2 = exercise.objects.filter(type=1).order_by('?')[:5]
            exercise_obj3 = exercise.objects.filter(type=2).order_by('?')[:5]
            # exercise_obj = exercise.objects.all()
            Test_Paper.objects.all().delete()
            test_paper = Test_Paper()
            test_paper.save()
            test_paper_id = test_paper.id
            print(test_paper_id)

            for one in exercise_obj1:
                test_paper_exercise = Test_Paper_Exercise()
                test_paper_exercise.stem = one.stem
                test_paper_exercise.type = one.type
                test_paper_exercise.test_paper_id = test_paper_id
                test_paper_exercise.save()

                for options in one.options_set.all():
                    test_paper_options = Test_Paper_options()
                    print(options.options)
                    test_paper_options.options = options.options
                    print(options.content)
                    test_paper_options.content = options.content
                    print(test_paper_exercise.id)
                    test_paper_options.exercise_id = test_paper_exercise.id
                    test_paper_options.save()

                for answer in one.answer_set.all():
                    test_paper_answer = Test_Paper_Answer()
                    print(answer.options)
                    test_paper_answer.options = answer.options
                    test_paper_answer.exercise_id = test_paper_exercise.id
                    test_paper_answer.save()

            for one in exercise_obj2:
                test_paper_exercise = Test_Paper_Exercise()
                test_paper_exercise.stem = one.stem
                test_paper_exercise.type = one.type
                # test_paper_exercise.explain = one.explain
                test_paper_exercise.test_paper_id = test_paper_id
                test_paper_exercise.save()

                for options in one.options_set.all():
                    test_paper_options = Test_Paper_options()
                    print(options.options)
                    test_paper_options.options = options.options
                    print(options.content)
                    test_paper_options.content = options.content
                    print(test_paper_exercise.id)
                    test_paper_options.exercise_id = test_paper_exercise.id
                    test_paper_options.save()

                for answer in one.answer_set.all():
                    test_paper_answer = Test_Paper_Answer()
                    # Summary = summary()
                    print(answer.options)
                    test_paper_answer.options = answer.options
                    test_paper_answer.exercise_id = test_paper_exercise.id
                    # Summary.exercise_id = test_paper_exercise.id
                    test_paper_answer.save()
                    # Summary.save()
            for one in exercise_obj3:
                test_paper_exercise = Test_Paper_Exercise()
                test_paper_exercise.stem = one.stem
                test_paper_exercise.type = one.type
                # test_paper_exercise.explain = one.explain
                test_paper_exercise.test_paper_id = test_paper_id
                test_paper_exercise.save()

                for options in one.options_set.all():
                    test_paper_options = Test_Paper_options()
                    print(options.options)
                    test_paper_options.options = options.options
                    print(options.content)
                    test_paper_options.content = options.content
                    print(test_paper_exercise.id)
                    test_paper_options.exercise_id = test_paper_exercise.id
                    test_paper_options.save()

                for answer in one.answer_set.all():
                    test_paper_answer = Test_Paper_Answer()
                    # Summary = summary()
                    print(answer.options)
                    test_paper_answer.options = answer.options
                    test_paper_answer.exercise_id = test_paper_exercise.id
                    # Summary.exercise_id = test_paper_exercise.id
                    test_paper_answer.save()
                    # Summary.save()

            return render(request, 'practice.html')
        else:
            return redirect(request.GET.get('from', reverse('welcome')))


def TestPaperShow(request):
    if request.session.get('is_login', None):
        if request.method == 'POST':
            question = models.Test_Paper_Exercise.objects.values("id").order_by('id')
            print(question)
            lst = []
            for p in question:
                for key, values in p.items():
                    print(key, values)
                    lst.append(values)
            print(lst)
            for q in lst:
                Summary = summary()
                mychoice = request.POST.get(str(q))
                print(mychoice)
                Summary.yourchoice = mychoice
                Summary.exercise_id = q
                Summary.save()
            return redirect(request.GET.get('from', reverse('summarize')))
        else:
            global data2
            data = Test_Paper.objects.all()
            # print(data, data.test_paper_subject_set.all())
            for one in data:
                data2 = one.test_paper_exercise_set.all()
                print(data2)
            return render(request, 'exercise.html', {'object_list': data2})
    else:
        return redirect(request.GET.get('from', reverse('welcome')))


def summarize(request):
    if request.session.get('is_login', None):
        data = summary.objects.all().order_by('exercise_id')
        data1 = Test_Paper_Answer.objects.all().order_by('exercise_id')
        data2 = Test_Paper_Exercise.objects.all().order_by('id')
        # print(data)
        return render(request, "summarize.html", {'object_list': data, 'object_list1': data1, 'object_list2': data2})
    else:
        return redirect(request.GET.get('from', reverse('welcome')))


def practice(request):
    return render(request, "practice.html")


def about(request):
    return render(request, "about.html")


def yx(request):
    return render(request, "yx.html")


def yx1(request):
    return render(request, "yx1.html")
